﻿using System;
using System.Linq;
using System.Threading;
using XTeam.Core.Interface;
using Newtonsoft.Json;

namespace XTeam.Core.Helper
{

    public class MessageEntity : IMessageEntity
    {
        public int InfoCode
        {
            get;
            set;
        }

        public string Message
        {
            get;
            set;
        }

        public int Level
        {
            get;
            set;
        }

        public override string ToString()
        {

            return JsonConvert.SerializeObject(this);
        }
    }

    public class MesageResultHelp : IMessageResult
    {
        DictionaryEx<int, IMessageEntity> _cache = new DictionaryEx<int, IMessageEntity>();
        public void WriteMessage(int infoCode, string msg, int level = (int)MessageLevel.Info)
        {
            // 总长度 65536
            if (_cache.Count > UInt16.MaxValue)
            {
                var key = _cache.Keys.ElementAt(0);
                _cache.Remove(key);
            }
            var temp = new MessageEntity() { InfoCode = infoCode, Message = msg, Level = level };
            _cache[Thread.CurrentThread.ManagedThreadId] = temp;

        }

        public IMessageEntity GetLastMessage()
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            var temp = _cache[threadId];
            _cache.Remove(threadId);
            return temp;
        }
    }

}
